// pages/confirmOrder/confirmOrder.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imageUrl: app.globalData.imageUrl,
    userInfo: '',
    adressData: {},
    hasAdress: false,
    productId: '',
    propertyId:'',
    addrsssId:'',
    goodsDetail: '',
    flag: 0,
    amount: 1,
    backupA:'',
    backup: '',
    shopCartId: [],
    submitData:{
      userId: '',
      total:'',
      amount:0,
      price:0,
      propertyId:'',
      youFei:'',
      shopId:'',
      productId:''
    },
    submit:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var _this = this;
    if (options.adressData != undefined) {
      this.setData({
        adressData: JSON.parse(options.adressData),
        hasAdress: true,
        addrsssId: _this.data.adressData.id
      })
    }
    else{
      this.getAddress()
    }                                          
    this.setData({
      code: wx.getStorageSync('code'),
      userInfo: JSON.parse(wx.getStorageSync('userInfo')),
      productId: options.productId,
      amount: options.amount,
      propertyId: options.propertyId
    })
    if(options.arr != undefined){  //购物车订单
      let arr = JSON.parse(options.arr),
          cartId = [],
          money = 0;
      for(var t = 0 ; t < arr.length; t++){
        money += (arr[t].shopMoney*100);
        for (var r = 0; r < arr[t].wareList.length; r++){
          cartId.push(arr[t].wareList[r].id)
        }
      }
      _this.setData({
        shopCartId: cartId.join(";"),
        totalMoney: money / 100,
        goodsDetail: arr,
        flag:1
      })
      _this.saveDataAll();
    }
    else{
      this.getGoodInfo(options.productId, options.amount, options.propertyId);
    }
    
  },
  // 获取买家留言信息
  inputFunc: function(e){
    let oIndex = e.currentTarget.dataset.index,
        shop = JSON.parse(this.data.submit);
    shop[oIndex].backupA = e.detail.value;
    this.data.submit = JSON.stringify(shop);
  },
  // 查询商品信息
  getGoodInfo: function (id, amount,attrId) {
    var _this = this;
    wx.request({
      url: app.globalData.httpApiCar + 'shopThing/getOne',
      data: {
        id: id
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        var obj = res.data.data;
        obj.propertyId = attrId;
        obj.amount = amount;
        obj.realThingShowImg = obj.realThingShowImg.split(",");
        _this.setData({
          ['goodsDetail[0].wareList[0]']: obj, 
          ['goodsDetail[0].amount']: amount,
          ['goodsDetail[0].shopMoney']: amount * obj.price + obj.thingFare,
          ['totalMoney']: ((amount * obj.price*100) + (obj.thingFare *100))/100
        })
        _this.saveData();
      }
    })
  },
  // 提交数据格式
  saveData() {
    var arr = [],
      obj = {};
    if (this.data.goodsDetail){
      var detail = this.data.goodsDetail[0].wareList[0];
      obj.userId = JSON.parse(wx.getStorageSync('userInfo')).id;
      obj.shopId = detail.shopId;
      obj.productId = detail.id;
      obj.amount = detail.amount;
      obj.price = detail.price;
      obj.propertyId = detail.propertyId;
      obj.youFei = detail.thingFare;
    }
    obj.addrsssId = this.data.addrsssId;
    arr.push(obj);
    this.data.submit = JSON.stringify(arr);
  },
  saveDataAll() {
    var arr = [];
    for (var i = 0; i < this.data.goodsDetail.length; i++){
      for (var j = 0; j < this.data.goodsDetail[i].wareList.length; j++){
        var detail = this.data.goodsDetail[i].wareList[j];
        var obj = {};
        obj.userId = JSON.parse(wx.getStorageSync('userInfo')).id;
        obj.shopId = detail.shopId;
        obj.productId = detail.shopThing.id;
        obj.amount = detail.amount;
        obj.price = detail.price;
        obj.propertyId = detail.propertyId;
        obj.youFei = detail.thingFare;
        obj.addrsssId = this.data.addrsssId;
        arr.push(obj);
      }
      this.data.submit = JSON.stringify(arr);
    } 
  },
  // 查询收货地址
  getAddress: function () {
    var _this = this;
    wx.request({
      url: app.globalData.httpApiCar + 'userAddress/page',
      data: {
        userId: JSON.parse(wx.getStorageSync('userInfo')).id
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        if (res.data.success) {
          for (var i = 0; i < res.data.data.pp.length; i++){
            if (res.data.data.pp[i].type == 1){
              _this.setData({
                adressData: res.data.data.pp[i],
                hasAdress: true,
                addrsssId: res.data.data.pp[i].id,
              })
            }
          }
          if(_this.data.flag == 1){
            _this.saveDataAll();
          }
          else {
            _this.saveData();
          }
        }
        else {
          wx.showToast({
            title: res.data.error,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  // 提交订单
  submitOrder: function (e) {
    var _this = this;
    wx.showLoading({
      title: '提交中',
    })
    console.info(_this.data.submit)
    var submitInfo = JSON.parse(_this.data.submit);
    var backup = (Math.random()+'').split(".")[1] + '' + new Date().getTime();
    for (var z = 0; z < submitInfo.length; z++){
      submitInfo[z].backupB = backup;
    }
    _this.data.submit = JSON.stringify(submitInfo);
    console.info(_this.data.submit)
    if (submitInfo[0].addrsssId != ''){
      wx.request({
        url: app.globalData.httpApiCar + 'shopOrder/saveList',
        data: {orderInfos:_this.data.submit},
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded' // 默认值
        },
        success: function (res) {
          if(res.data.success){
            _this.setData({
              backup: backup
            })
            if(_this.data.flag == 1){
              _this.delShopCart(_this.data.shopCartId)

            }
            else{
              wx.hideLoading();
            }
            _this.payMoney(backup, submitInfo[0].shopId)
          }
          else{
            wx.hideLoading();
            wx.showToast({
              title: res.data.error,
              icon: 'none',
              duration: 2000
            })
          }
        }
      })
    }
    else{
      wx.showToast({
        title: '请选择收货地址',
        icon: 'none',
        duration: 2000
      })
    }
  },
  payMoney: function (backup, backupE) {
    var that = this;
    wx.request({
      url: app.globalData.httpApiCar + 'shopOrder/payTheBill',
      data: {
        openId: app.globalData.openId,
        backupB: backup,
        backupE: backupE,
        backupC: 6,
        userId: that.data.userInfo.id,
        money: that.data.totalMoney,
        body: '购买商品支付费用'
      },
      success: function (res) {
        if (res.data.success) {
          that.requestPayment(res.data.data);
        }
        else {
          wx.showToast({
            title: res.data.error,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  requestPayment: function (obj) {
    var that = this;
    wx.requestPayment({
      'timeStamp': obj.timeStamp,
      'nonceStr': obj.nonceStr,
      'package': obj.package,
      'signType': obj.signType,
      'paySign': obj.paySign,
      'success': function (res) {
        that.getMoney(2)
      },
      'fail': function (res) {
        wx.showModal({
          title: '提示',
          content: '支付失败',
          showCancel: false,
          success: function (res) {
            that.getMoney(1)
            if (res.confirm) {
            }
          }
        })
      }
    })
  },
  // 删除购物车商品
  delShopCart: function(id){
    var _this = this;
    wx.request({
      url: app.globalData.httpApiCar + 'shoppingCart/delAll',
      data: { ids:id},
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success: function (res) {
        if(res.data.success){
          wx.hideLoading();
          // _this.payMoney()
        }
      }
    })
  },
  // 交易记录
  moneyList: function (money, adds) {
    var _this = this;
    wx.request({
      url: app.globalData.httpApiCar + 'userPayInfo/save',
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      method: 'POST',
      data: {
        userId: _this.data.userInfo.id,
        adds: adds,
        money: money
      },
      success: function (res) {

      }
    })
  },
  // 确认
  getMoney(status) {
    var _this = this;
    wx.request({
      url: app.globalData.httpApiCar + 'shopOrder/update',
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      method: 'POST',
      data: {
        backupB: _this.data.backup,
        shopPay: 2,
        orderStatus: status
      },
      success: function (res) {
        if (res.data.success) {
          // _this.moneyList(_this.data.totalMoney, 1)
          wx.redirectTo({
            url: '/pages/myOrder/myOrder'
          })
        }
        else {
          wx.showToast({
            title: res.data.error,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  // 选择地址
  chooseAdress: function (e) {
    var obj = {};
    obj.productId = this.data.productId;
    obj.amount = this.data.amount;
    obj.propertyId = this.data.propertyId;
    wx.setStorageSync('address', obj);
    wx.navigateTo({
      url: '/pages/adressMana/adressMana'
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})